package com.csproj.basic.resource;

import com.codahale.metrics.annotation.Timed;
import com.csproj.basic.domain.Site;
import com.csproj.basic.service.SiteService;
import com.csproj.basic.service.dto.FixedReadingDeviceDTO;
import com.csproj.basic.service.dto.SiteDTO;
import com.csproj.basic.service.mapper.SiteMapper;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * REST controller for managing Site.
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class SiteResource {

    private final Logger log = LoggerFactory.getLogger(SiteResource.class);

    private final SiteService siteService;
    private  final SiteMapper siteMapper;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;

    public SiteResource(SiteService siteService,
                        UserInfoService userInfoService,
                        SiteMapper siteMapper,
                        SysLogsService sysLogsService) {
        this.siteService = siteService;
        this.userInfoService =userInfoService;
        this.siteMapper = siteMapper;
        this.sysLogsService =sysLogsService;
    }

    /**
     * POST  /sites : 创建站点.
     * @param siteDTO 站点DTO
     * @return
     * TODO 保存post方法
     * TODO 每个方面里面都要加try catch处理
     */
    @PostMapping("/sites")
    @Timed
    public BaseDTO createSite(@Valid @RequestBody SiteDTO siteDTO){
        SiteDTO result = siteService.saveAndGetDTO(siteDTO);
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_create_site","");
        return BaseDTO.createBaseDTO().setResult(result);
    }

    /**
     * PUT  /sites : 修改站点信息.
     * @param siteDTO 站点DTO
     * @return
     */
    @PutMapping("/sites/{id}")
    @Timed
    public BaseDTO updateSite(@Valid @RequestBody SiteDTO siteDTO, @PathVariable String id) throws URISyntaxException {
        siteDTO.setId(id);
        SiteDTO result = siteService.updateAndGetDTO(siteDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_site","");
        return BaseDTO.createBaseDTO().setResult(result);
    }

    /**
     * GET  /sites : 获取站点信息.
     * @return 站点信息
     */
    @GetMapping("/sites")
    @Timed
    public BaseDTO getPageSites(@RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                @RequestParam(value = "siteName",required = false) String siteName,
                                @RequestParam(value = "siteType",required = false) String siteType) {
        Pageable pageable = PageableTools.basicPage(pageNum,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("siteName",siteName);
        map.put("siteType",siteType);
        BaseDTO result = siteService.findPageListAndGetDTO(map,pageable);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_view_site_list","");
        return result;
    }


    /**
     * GET  /sites : 获取站点信息(不分页)
     * @return BaseDTO
     */
    @GetMapping("/allsites")
    @Timed
    public BaseDTO getAllSites() {
        return BaseDTO.createBaseDTOByFieldList(siteService.findAllEnabled());
    }

    /**
     * GET  /sites : 获取站点信息(不分页)
     * @return BaseDTO
     */
    @GetMapping("/allsitesbyid")
    @Timed
    public BaseDTO getAllSitesBySite()
    {
        String siteId = userInfoService.getCurrentUserSiteId();
        if(StringUtils.isNotBlank(siteId)&& siteId!="nositeID")
        {
            Site site = siteService.findOne(siteId);
            SiteDTO siteDTO = siteMapper.toDto(site);
            List<SiteDTO> list = new ArrayList<>();
            list.add(siteDTO);
            return BaseDTO.createBaseDTOByFieldList(list);
        }
        else
        {
            return BaseDTO.createBaseDTOByFieldList(siteService.findAllEnabled());
        }
    }
    /**
     * GET  /sites/:id : 根据站点id，获取站点信息
     *
     * @param id 站点id
     * @return 机构信息
     */
    @GetMapping("/sites/{id}")
    @Timed
    public BaseDTO getSite(@PathVariable String id) {
        SiteDTO siteDTO = siteService.findOneAndGetDTO(id);
        return BaseDTO.createBaseDTO().setResult(siteDTO);
    }

    /**
     * DELETE  /sites/:id : 根据id，删除站点信息.
     * @param id id
     * @return
     */
    @DeleteMapping("/sites/{id}")
    @Timed
    public BaseDTO deleteSite(@PathVariable String id) {
        siteService.delete(id);
        return BaseDTO.createBaseDTO();
    }

    /**
     * PUT  /sites/updateSiteStatus/{id} : 修改站点使用状态
     *
     * @param siteDTO
     * @param id
     * @return BaseDTO
     * @throws URISyntaxException
     */
    @PutMapping("/sites/updateSiteStatus/{id}")
    @Timed
    public BaseDTO updateSiteStatus(HttpServletRequest request, @RequestBody(required = false) SiteDTO siteDTO, @PathVariable String id) throws URISyntaxException {
        log.debug("REST request to update UserInfo isUse : {}", siteDTO);
        siteDTO.setId(id);
        SiteDTO result = siteService.updateSiteStatus(siteDTO);
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":update_site_status","");
        return BaseDTO.createBaseDTO(result).setMessage("update_site_success");
    }

    /**
     *  批量导入
     */
    @PostMapping("/sites/batchImport")
    @Timed
    public BaseDTO siteBatchImport(MultipartFile file){
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":batch_upload_site","");
        return siteService.batchImport(file) ;
    }

}